package com.sia.springcloud.service.impl;

import com.alibaba.fastjson.JSON;
import com.sia.springcloud.model.Device;
import com.sia.springcloud.mapper.DeviceMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sia.springcloud.service.IDeviceService;
import com.sia.springcloud.result.GridDataResult;
import com.sia.springcloud.result.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 * 通信协议设备表 服务实现类
 * </p>
 *
 * @author Sirius
 * @since 2021-12-27
 */
@Slf4j
@Service
public class DeviceService extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private ProtocolService protocolService;

    /**
     * 插入设备
     *
     * @param request
     * @return
     */
    @Override
    public String insertDevice(HttpServletRequest request) {
        log.info("插入设备");

        String instanceId = getInstanceIdByProtocolName(request);
        if(instanceId==null){
            return ResultUtil.createSimpleFailureJson("协议对应的微服务未启动");
        }else {
            String priorityUrl = "http://" + instanceId + "/deviceController/insertDevice";
            MultiValueMap<String, Object> params = packingParams(request);
            return restTemplate.postForObject(priorityUrl, params, String.class);
        }
    }

    /**
     * 分页查询设备
     *
     * 如果该协议微服务正在运行，就返回查询结果，否则返回
     *
     * @param request
     * @return
     */
    @Override
    public String queryDevice(HttpServletRequest request) {
        log.info("查询设备");
        String instanceId = getInstanceIdByProtocolName(request);
        if (instanceId == null) {
            GridDataResult<Device> deviceListResult = new GridDataResult<>();
            deviceListResult.setTotal(0);
            deviceListResult.setRoot(null);
            return JSON.toJSONString(deviceListResult);
        } else {
            String priorityUrl = "http://" + instanceId + "/deviceController/queryDevice";
            MultiValueMap<String, Object> params = packingParams(request);
            return restTemplate.postForObject(priorityUrl, params, String.class);
        }
    }

    /**
     * 批量删除设备
     *
     * @param request
     * @return
     */
    @Override
    public String deleteDevice(HttpServletRequest request) {
        log.info("删除设备");
        String instanceId = getInstanceIdByProtocolName(request);
        log.info("instanceId:{}"+instanceId);
        if(instanceId==null){
            return ResultUtil.createSimpleFailureJson("协议对应的微服务未启动");
        }else {
            String priorityUrl = "http://" + instanceId + "/deviceController/deleteDevice";
            MultiValueMap<String, Object> params = packingParams(request);
            return restTemplate.postForObject(priorityUrl, params, String.class);
        }
    }

    /**
     * 更新设备
     *
     * @param request
     * @return
     */
    @Override
    public String updateDevice(HttpServletRequest request) {
        log.info("更新设备");
        String instanceId = getInstanceIdByProtocolName(request);
        if(instanceId==null){
            return ResultUtil.createSimpleFailureJson("协议对应的微服务未启动");
        }else {
            String priorityUrl = "http://" + instanceId + "/deviceController/updateDevice";
            MultiValueMap<String, Object> params = packingParams(request);
            return restTemplate.postForObject(priorityUrl, params, String.class);
        }
    }


    /**
     * 获取设备表单格式
     *
     * @param request
     * @return
     */
    @Override
    public String tableStructure(HttpServletRequest request) {
        log.info("获取设备表结构");
        String instanceId = getInstanceIdByProtocolName(request);
        if(instanceId==null){
            return ResultUtil.createSimpleFailureJson("协议对应的微服务未启动");
        }else {
            String priorityUrl = "http://" + instanceId + "/deviceController/tableStructure";
            MultiValueMap<String, Object> params = packingParams(request);
            return restTemplate.postForObject(priorityUrl, params, String.class);
        }
    }



    /**
     * 根据协议名获取对应的微服务实例路径
     * 如果存在就返回
     * 没有就返回null
     *
     * @param request
     * @return
     */
    private String getInstanceIdByProtocolName(HttpServletRequest request) {
        return protocolService.getInstanceIdByProtocolName(request);
    }

    /**
     * 对request中的参数进行包装
     *
     * @param request
     * @return
     */
    private MultiValueMap<String, Object> packingParams(HttpServletRequest request) {
        // 复制 request 的参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<String, Object>();
        // 附加参数值
        Set<String> keySet = parameterMap.keySet();
        for (String key : keySet) {
            String[] value = parameterMap.get(key);
            params.add(key, value[0]);
        }
        return params;
    }


}
